package cn.edu.zut.mock;

import cn.edu.zut.bean.Car;
import com.github.javafaker.Faker;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;

public class CarDataGenerator {
    private static final String DB_URL = "jdbc:mysql://hadoop102:3306/driver?allowPublicKeyRetrieval=true&useSSL=false&requireSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "000000";
    private static final int BATCH_SIZE = 100;
    // 缓存 driver_ids 避免重复查询
    private static List<String> driverIdCache = null;
    private static final Random random = new Random();

    /**
     * 从 driver 表中随机获取一个 driver_id
     */
    public static String randomDriverId() {
        if (driverIdCache == null || driverIdCache.isEmpty()) {
            driverIdCache = getAllDriverIds();
        }

        if (driverIdCache == null || driverIdCache.isEmpty()) {
            throw new IllegalStateException("driver 表中没有可用的 driver_id");
        }

        return driverIdCache.get(random.nextInt(driverIdCache.size()));
    }

    /**
     * 查询所有 driver_id
     */
    public static List<String> getAllDriverIds() {
        List<String> driverIds = new ArrayList<>();
        String query = "SELECT driver_id FROM driver";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(query)) {

            while (rs.next()) {
                driverIds.add(rs.getString("driver_id"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (driverIds.isEmpty()) {
            throw new RuntimeException("driver 表中没有可用的 driver_id");
        }

        return driverIds;
    }

    /**
     * 获取 driver 表中指定 driver_id 的 car_number, car_type, total_orders
     */
    public static DriverInfo getDriverInfoById(String driverId) {
        String query = "SELECT driver_car_number, driver_car_type, total_orders FROM driver WHERE driver_id = ?";
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(query)) {

            pstmt.setString(1, driverId);

            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return new DriverInfo(
                            rs.getString("driver_car_number"),
                            rs.getString("driver_car_type"),
                            rs.getString("total_orders")
                    );
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 用于保存 driver 表中需要的字段信息
     */
    private static class DriverInfo {
        String carNumber;
        String carType;
        String totalOrders;

        public DriverInfo(String carNumber, String carType, String totalOrders) {
            this.carNumber = carNumber;
            this.carType = carType;
            this.totalOrders = totalOrders;
        }
    }

    public static void main(String[] args) {
        // 每次运行追加10条数据
        int count = 10;
        generateData(count);
    }

    public static void generateData(int count) {
        Faker faker = new Faker(Locale.CHINA);
        List<Car> cars = new ArrayList<>();

        // 获取数据库中已有的最大car_id
        long startId = getMaxCarId() + 1;

        for (long i = startId; i < startId + count; i++) {
            String driverId = randomDriverId();
            DriverInfo info = getDriverInfoById(driverId);

            if (info == null) {
                System.err.println("无法找到 driver_id = " + driverId + " 的信息");
                continue;
            }

            Car car = Car.builder()
                    .car_id(String.valueOf(i))
                    .driver_id(driverId)
                    .car_type(info.carType)
                    .car_number(info.carNumber)
                    .car_color(generateRandomCarColor(faker))
                    .car_brand(generateRandomCarBrand(faker))
                    .car_seat(generateRandomCarSeat(faker))
                    .total_orders(info.totalOrders)
                    .avg_distance(generateRandomAvgDistance(faker))
                    .build();
            cars.add(car);
        }

        // 批量插入数据库
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            conn.setAutoCommit(false);
            String sql = "INSERT INTO car (car_id, driver_id, car_type, car_number, car_color, car_brand, car_seat, total_orders, avg_distance) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                for (int i = 0; i < cars.size(); i++) {
                    Car car = cars.get(i);
                    pstmt.setString(1, car.getCar_id());
                    pstmt.setString(2, car.getDriver_id());
                    pstmt.setString(3, car.getCar_type());
                    pstmt.setString(4, car.getCar_number());
                    pstmt.setString(5, car.getCar_color());
                    pstmt.setString(6, car.getCar_brand());
                    pstmt.setString(7, car.getCar_seat());
                    pstmt.setString(8, car.getTotal_orders());
                    pstmt.setDouble(9, car.getAvg_distance());
                    pstmt.addBatch();

                    if ((i + 1) % BATCH_SIZE == 0) {
                        pstmt.executeBatch();
                    }
                }
                pstmt.executeBatch();
                conn.commit();
                System.out.println("成功插入" + count + "条车辆数据");
            } catch (SQLException e) {
                conn.rollback();
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询数据库中已有的最大car_id
     */
    private static long getMaxCarId() {
        String sql = "SELECT MAX(CAST(car_id AS SIGNED)) FROM car"; // 替换为你的表名
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            if (rs.next()) {
                return rs.getLong(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0; // 如果表为空，返回0
    }

    private static double generateRandomAvgDistance(Faker faker) {
        return Math.round(faker.number().randomDouble(2, 15, 300) * 100.0) / 100.0;
    }

    private static String generateRandomCarSeat(Faker faker) {
        String[] seats = {"2座", "4座", "5座", "7座", "8座", "10座"};
        return seats[faker.random().nextInt(seats.length)];
    }

    private static String generateRandomCarColor(Faker faker) {
        String[] colors = {"红色", "蓝色", "黄色", "绿色", "紫色", "橙色", "黑色", "白色", "棕色", "灰色"};
        return colors[faker.random().nextInt(colors.length)];
    }

    private static String generateRandomCarType(Faker faker) {
        String[] carTypes = {"SUV", "MPV", "轿车", "面包车", "商务车", "皮卡"};
        return carTypes[faker.random().nextInt(carTypes.length)];
    }

    public static String generateRandomCarBrand(Faker faker) {
        String[] brands = {"比亚迪", "丰田", "福特", "吉利", "长城", "本田", "大众", "宝马", "奔驰", "标致", "奥迪", "雪佛兰", "沃尔沃", "奇瑞", "五菱", "路虎", "捷豹"};
        return brands[faker.random().nextInt(brands.length)];
    }
}